﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;

namespace Cosoware.Web.ResponseFilters
{
    /// <summary>
    /// Counts number of writes to the response stream.
    /// </summary>
    class WritesStatisticModule : IHttpModule
    {
        /// <summary>
        /// The current application
        /// </summary>
        private HttpApplication _context;

        private readonly Dictionary<HttpResponse, CounterFilterStream> _streams = new Dictionary<HttpResponse, CounterFilterStream>();

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            _context = context;
            _context.BeginRequest += new EventHandler(RegisterFilter);
            _context.PreSendRequestContent += new EventHandler(AddStatistics);
        }

        private void RegisterFilter(object sender, EventArgs e)
        {
            _context.Response.Filter = _streams[_context.Response] = new CounterFilterStream(_context.Response.Filter);
        }

        /// <summary>
        /// Adds statistics of writes to header.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void AddStatistics(object sender, EventArgs e)
        {
            var filter = _streams[_context.Response];
            _streams.Remove(_context.Response);
            _context.Response.Write("<!-- Writes during response: ");
            _context.Response.Write(filter.WritesCount.ToString());
            _context.Response.Write(" -->");
        }

        /// <summary>
        /// Disposes of the resources.
        /// </summary>
        public void Dispose()
        {
        }
    }
}
